﻿using System;
using System.Collections.Generic;
using System.Web.Security;
using Hxsoft.AppV1;

namespace Hxsoft.AppV1.Module
{
	public class WebAppContext : IAppContext
	{
		#region IAppContext 成员
		public Guid? CurrentUserId
		{
			get { return GetCurrentUserId(false); }
		}

		public User CurrentUser
		{
			get { return GetCurrentUser(false); }
		}

		public string CurrentUserName
		{
			get { return GetCurrentUserName(false); }
		}

		public Guid? GetCurrentUserId(bool userIsOnline)
		{
			MembershipUser mUser = Membership.GetUser(userIsOnline);
			if (mUser != null)
				return (Guid)mUser.ProviderUserKey;
			return null;
		}

		public User GetCurrentUser(bool userIsOnline)
		{
			MembershipUser mUser = Membership.GetUser(userIsOnline);
			User user = new User();
			return Users.MembershipToUser(mUser, user);
		}

		public string GetCurrentUserName(bool userIsOnline)
		{
			MembershipUser mUser = Membership.GetUser(userIsOnline);
			if (mUser != null)
				return mUser.UserName;
			return null;
		}

		public int? CurrentSiteId
		{
			get
			{
				Site site = CurrentSite;
				if (site != null) return site.SiteId;
				return null;
			}
		}

		private static Site currentSite;
		public Site CurrentSite
		{
			get
			{
				GenericModuleDataContext dc;

				// 通过配置文件获取当前站点信息
				int? currentSiteId = ApplicationConfiguration.GetCurrentSiteId();
				if (currentSiteId.HasValue)
				{
					if (currentSite == null || currentSite.SiteId != currentSiteId.Value)
					{
						dc = new GenericModuleDataContext();
						dc.ObjectTrackingEnabled = false;
						currentSite = dc.Sites.GetItem(currentSiteId.Value);
					}
					return currentSite;
				}


				// 通过域名获取当前站点信息
				string currentDomain = System.Web.HttpContext.Current.Request.Url.Host.ToLower();
				return Sites.GetSiteByDomain(currentDomain);
			}
		}

		public bool Login(string userName, string password)
		{
			bool pass = Membership.ValidateUser(userName, password);
			if (pass)
				FormsAuthentication.SetAuthCookie(userName, false);

			return pass;
		}

		public bool Logout(string userName)
		{
			FormsAuthentication.SignOut();
			return true;
		}
		#endregion
	}
}